package ${basePackage}.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import ${basePackage}.mapper.${modelNameUpperCamel}Mapper;
import ${basePackage}.entity.${modelNameUpperCamel};
import ${basePackage}.entity.vo.${modelNameUpperCamel}Vo;
import ${basePackage}.service.${modelNameUpperCamel}Service;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * ${modelNameUpperCamel}表服务实现类
 *
 * @author ${author}
 * @date ${date}
 */
@Slf4j
@Service("${modelNameLowerCamel}Service")
public class ${modelNameUpperCamel}ServiceImpl extends ServiceImpl
        <${modelNameUpperCamel}Mapper, ${modelNameUpperCamel}> implements ${modelNameUpperCamel}Service {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public boolean saveOne(${modelNameUpperCamel} ${modelNameLowerCamel}) {
        commonService.setCreateAndModifyInfo(${modelNameLowerCamel});
       // ${modelNameLowerCamel}.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validParamRequired(${modelNameLowerCamel});
        validRepeat(${modelNameLowerCamel});
        validParamFormat(${modelNameLowerCamel});
        return save(${modelNameLowerCamel});
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(${modelNameUpperCamel} ${modelNameLowerCamel}) {
        Assert.notNull(${modelNameLowerCamel}.getId(), "id不能为空");
        commonService.setModifyInfo(${modelNameLowerCamel});
        //${modelNameLowerCamel}.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(${modelNameLowerCamel});
        validParamFormat(${modelNameLowerCamel});
        return updateById(${modelNameLowerCamel});
    }

    @Override
    public IPage<${modelNameUpperCamel}> selectPage(Page page, ${modelNameUpperCamel} ${modelNameLowerCamel}) {
        //${modelNameLowerCamel}.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, ${modelNameLowerCamel});
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(${modelNameUpperCamel} ${modelNameLowerCamel}, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<${modelNameUpperCamel}> page = selectPage(new Page(0, -1), ${modelNameLowerCamel});
        List<${modelNameUpperCamel}> records = page.getRecords();
        List
                <${modelNameUpperCamel}Vo> ${modelNameLowerCamel}Vos = new ArrayList<>();
        for (${modelNameUpperCamel} expert : records) {
            ${modelNameLowerCamel}Vos.add(new ${modelNameUpperCamel}Vo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "${modelNameUpperCamel}导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, ${modelNameLowerCamel}Vos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public ${modelNameUpperCamel} getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(${modelNameUpperCamel} ${modelNameLowerCamel}) {
        /* QueryWrapper<${modelNameUpperCamel}> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", ${modelNameLowerCamel}.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<${modelNameUpperCamel}> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(${modelNameLowerCamel}.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!${modelNameLowerCamel}.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(${modelNameUpperCamel} ${modelNameLowerCamel}) {
        //Assert.notNull(${modelNameLowerCamel}, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(${modelNameLowerCamel}.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(${modelNameUpperCamel} ${modelNameLowerCamel}) {
        //Assert.isTrue(${modelNameLowerCamel}.getName() == null || ${modelNameLowerCamel}.getName().length() <= 50,
        //        "名称超长");
    }
}

